package com.dingding.queue.queue.consumer.listener;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.dingding.common.core.beans.special.UserspecialorderT;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.facade.special.ISpecialOrderFacade;

@Component("appointSpecialOrderListener")
public class AppointSpecialOrderListener implements MessageListener {

	@Resource(name = "specialOrderFacade")
	private ISpecialOrderFacade specialOrderFacade;

	@Override
	public Action consume(Message message, ConsumeContext context) {

		Logger log = Logger.getLogger(this.getClass());

		String request = "";
		try {
			request = new String(message.getBody(), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			log.error("指派订单过程中产生错误！", e1);
			return Action.ReconsumeLater;
		}
		UserspecialorderT userspecialorderT = JSONUtil.parseObject(request, UserspecialorderT.class);

		// 如果订单为实时订单
		if (userspecialorderT.getSetOutType() == 1) {

			try {
				if (this.specialOrderFacade.appointRealOrder(userspecialorderT)) {
					return Action.CommitMessage;
				} else {
					return Action.ReconsumeLater;
				}
			} catch (Exception e) {
				log.error("指派订单过程中产生错误！", e);
				return Action.CommitMessage;
			}

			// 如果订单为预约订单
		} else if (userspecialorderT.getSetOutType() == 2) {

			try {
				if (this.specialOrderFacade.appointUnRealOrder(userspecialorderT)) {
					return Action.CommitMessage;
				} else {
					return Action.ReconsumeLater;
				}
			} catch (Exception e) {
				log.error("指派订单过程中产生错误！", e);
				return Action.CommitMessage;
			}

		} else {
			return Action.CommitMessage;
		}
	}

}
